<?php

namespace app\admin\controller\api;

use app\admin\library\DistinguishAddress;
use app\common\model;

/**
 * 课程
 * @internal
 */
class Course extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 课程考勤信息
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $course_detail_id = $this->request->request('course_id');
        $student_id = $this->request->request('student_id');

        $student = model\Student::alias('student')
            ->join('__CLASSES__ class', 'class.id = student.class_id', 'left')
            ->join('__GRADE__ grade', 'grade.id = class.grade_id', 'left')
            ->where('student.id', $student_id)
            ->field('student.id,student.name,student.number,student.gender,class.id class_id,class.name class_name,grade.id grade_id,grade.name grade_name')
            ->find();

        if (!$student) {
            $this->error('学生不存在');
        }

        $result = model\CourseDetail::alias('course_detail')
            ->join('__TEACH__ teach', 'teach.id = course_detail.teach_id')
            ->join('__CLASSES__ class', 'class.id = course_detail.class_id', 'left')
            ->join('__GRADE__ grade', 'grade.id = class.grade_id', 'left')
            ->join('__CLASSROOM__ room', 'room.id = class.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = room.building_id', 'left')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id', 'left')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->field('course_detail.id,course_detail.number,course_detail.day,teach.class_ids,grade.id grade_id,grade.name grade_name,class.school_id,course_detail.class_id,class.name class_name,class.classroom_id,room.name classroom_name,room.building_id,building.name building_name,teach.subject_id,subject.name subject_name,teach.teacher_id,teach.is_clock_in,teach.clock_in_time,user.nickname teacher_name')
            ->where('course_detail.id', $course_detail_id)
            ->find();

        $class_ids = explode(',', $result['class_ids']);
        if (!in_array($student->class_id, $class_ids)) {
            $this->error('当前课程不允许考勤');
        }

        $class_day = model\ClassDay::where([
            'school_id' => $result['school_id'],
            'number' => $result['number'],
            'day' => $result['day'],
        ])->find();

        $result['start_time'] = $class_day['start_time'];
        $result['end_time'] = $class_day['end_time'];
        $result['student'] = $student;

        $this->success('', $result);

    }

}